import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import axiosInstance from '../api/axiosInstance';
import { Container, TextField, Button, Typography, Box } from '@mui/material';

const EditRadiologist = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const [radiologist, setRadiologist] = useState({
    first_name: '',
    last_name: '',
    modality: '',
    rate: ''
  });

  useEffect(() => {
    const fetchRadiologist = async () => {
      try {
        const response = await axiosInstance.get(`api/radiologists/${id}/`);
        setRadiologist(response.data);
      } catch (error) {
        console.error('Ошибка при загрузке данных врача:', error);
      }
    };

    fetchRadiologist();
  }, [id]);

  const handleChange = (e) => {
    setRadiologist({ ...radiologist, [e.target.name]: e.target.value });
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      await axiosInstance.put(`api/radiologists/${id}/`, radiologist);
      navigate('/radiologists');
    } catch (error) {
      console.error('Ошибка при обновлении данных врача:', error);
    }
  };

  return (
    <Container maxWidth="sm">
      <Box
        display="flex"
        flexDirection="column"
        alignItems="center"
        justifyContent="center"
        minHeight="100vh"
      >
        <Typography variant="h4" component="h1" gutterBottom>
          Редактировать Врача
        </Typography>
        <form onSubmit={handleSubmit} style={{ width: '100%' }}>
          <TextField
            label="Имя"
            name="first_name"
            value={radiologist.first_name}
            onChange={handleChange}
            fullWidth
            margin="normal"
            variant="outlined"
          />
          <TextField
            label="Фамилия"
            name="last_name"
            value={radiologist.last_name}
            onChange={handleChange}
            fullWidth
            margin="normal"
            variant="outlined"
          />
          <TextField
            label="Модальность"
            name="modality"
            value={radiologist.modality}
            onChange={handleChange}
            fullWidth
            margin="normal"
            variant="outlined"
          />
          <TextField
            label="Ставка"
            name="rate"
            value={radiologist.rate}
            onChange={handleChange}
            fullWidth
            margin="normal"
            variant="outlined"
          />
          <Button
            type="submit"
            variant="contained"
            color="primary"
            fullWidth
            style={{ marginTop: '16px' }}
          >
            Сохранить
          </Button>
        </form>
      </Box>
    </Container>
  );
};

export default EditRadiologist;